package com.jfireframework.commonloggersolution;

public class ByteCache
{
    byte[] array;
    int    len;

    public ByteCache(int size)
    {
        array = new byte[size];
    }

    public ByteCache()
    {
        this(256);
    }

    private void ensureCapacity(int write)
    {
        if (len + write > array.length)
        {
            int    newLen   = array.length * 2 > write + len ? array.length * 2 : write + len;
            byte[] newArray = new byte[newLen];
            System.arraycopy(array, 0, newArray, 0, len);
            array = newArray;
        }
    }

    public void put(byte[] value)
    {
        ensureCapacity(value.length);
        System.arraycopy(value, 0, array, len, value.length);
        len += value.length;
    }

    public void put(byte value)
    {
        ensureCapacity(1);
        array[len] = value;
        len++;
    }

    public void putInt(int value)
    {
        ensureCapacity(4);
        array[len++] = (byte) (value >> 24);
        array[len++] = (byte) (value >> 16);
        array[len++] = (byte) (value >> 8);
        array[len++] = (byte) (value);
    }

    public void putShort(short value)
    {
        ensureCapacity(2);
        array[len++] = (byte) (value >> 8);
        array[len++] = (byte) (value);
    }

    public void putLong(long value)
    {
        ensureCapacity(8);
        array[len++] = (byte) (value >> 56);
        array[len++] = (byte) (value >> 48);
        array[len++] = (byte) (value >> 40);
        array[len++] = (byte) (value >> 32);
        array[len++] = (byte) (value >> 24);
        array[len++] = (byte) (value >> 16);
        array[len++] = (byte) (value >> 8);
        array[len++] = (byte) (value);
    }

    public byte[] toBytes()
    {
        byte[] result = new byte[len];
        System.arraycopy(array, 0, result, 0, len);
        return result;
    }
}
